package commands.forum {
	
	import devkit.commando.ICustomCommand;
	import devkit.commando.rpc.RPCBase;
	
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	
	/**
	 * Command to save a new forum post.
	 * @author Francois Dempers
	 */
	public class SavePost extends RPCBase implements ICustomCommand {
		
		public var header:String;
		public var body:String;
		
		/**
		 * Creates a new <code>SavePost</code> command.
		 * @param handler The function to invoke when a result is received.
		 */
		public function SavePost(handler:Function) {
			
			super(Session.rpcGateway, "groupSite.Forum", handler);
		}
		
		/**
		 * Validates all of the command arguments.
		 * @return <code>null</code> if the command was executed, otherwise an error code or message.
		 */
		public function validate():String {
			
			if(header == null || header.length > 50) {
				return "Header may be no more than 50 characters";
			} else if(body == null) {
				return "Body is required";
			}
			return null;
		}
		
		/**
		 * Executes the command.
		 * @return <code>null</code> if the command was executed, otherwise an error code or message.
		 */
		public function execute():String {
			
			var error:String = validate();
			if(error != null) {
				return error;
			}
			
			invoke("savePost", Session.sessionID, Session.userData.userID, header, body);
			
			return null;
		}
		
		/**
		 * Called when a result is received from the service.
		 * @param event The result event.
		 */
		public function result(event:ResultEvent):void {
			
			dispatchResult(event.result);
		}
		
		/**
		 * Called when a fault is received from the service.
		 * @param event The fault event.
		 */
		public function fault(event:FaultEvent):void {
			
			dispatchFault(HANDLE_BOTH, event);
		}
	}
}